import { Injectable } from '@angular/core';
import { exists, missing, type } from '../../utils/utils';
import { Router } from '@angular/router';
import { Events } from '@core/services/events/Events';
import { ReuseTabService } from '@shared/apes/reuse-tab';

let lifecycleHooks: string[];
lifecycleHooks = ['onInit', 'onChanges', 'doCheck', 'afterContentInit', 'afterContentChecked', 'afterViewInit', 'afterViewChecked', 'onDestroy'];

@Injectable()
export class FormService {
  public formData = {};

  constructor(
    private router: Router,
    protected events: Events,
    protected rs: ReuseTabService,
  ) {
  }


  /**
   * 功能：扩展表单元数据
   * @param metadata
   * @returns {any}
   */
  public extFormMetadata(metadata: any, ctx, subject, tableValid) {
    let t = type(metadata);
    if (t === 'array') {
      metadata.forEach(a => this.extFormMetadata(a, ctx, subject, tableValid));
    } else if (t === 'object') {
      for (let k in metadata) {
        let value = metadata[k];
        if (type(value) === 'string') {
          if (lifecycleHooks.includes(k)) {
            metadata[k] = (new Function('ctx, field, form, model, options', String(value))).bind(null, ctx);
          } else if (k === 'onDepends') {
            let functionBody = this.createOnDependsFunctionBody(value || undefined);
            if (exists(functionBody)) {
              let fn1 = new Function('ctx, field', functionBody);
              if (metadata.hooks.onInit) {
                let fn2;
                if (typeof metadata.hooks.onInit === 'function') {
                  fn2 = metadata.hooks.onInit;
                } else {
                  fn2 = new Function('ctx,field', String(metadata.hooks.onInit));
                }
                let fn3 = function(ctx, field, form, model, options) {
                  fn1(ctx, field, form, model, options);
                  fn2(ctx, field, form, model, options);
                };
                metadata.hooks.onInit = fn3.bind(null, ctx);
              } else {
                metadata.hooks.onInit = fn1.bind(null, ctx);
              }
            }
          } else if (k === 'tableValid') {
            subject.subscribe(ctx, value, data => {
              if (ctx.states !== 'submit') return;
              if (exists(data.params)) {
                tableValid[value] = data.params.valid;
              } else {
                /**表格行数据删除**/
                tableValid[value] = true;
              }
              ctx.valid = true;
              for (let key in tableValid) {
                if (!tableValid[key]) {
                  ctx.valid = false;
                  break;
                }
              }
            });
          } else if (k === 'validators') {
            if (value.indexOf(',') > -1) {
              value = value.split(',');
            }
            metadata[k] = { validation: [value] };
          } else if (k === 'hideExpression') {
            /*后期复杂表达式再自己解析*/
          }
        } else {
          this.extFormMetadata(value, ctx, subject, tableValid);
        }
      }
    }
  }

  /**
   * 功能：字段回填（onDepends配置回填）
   * @param element 字段元数据
   * @param params
   */
  private createOnDependsFunctionBody(onDependsMetadata: any): string {
    let functionBody = '';
    if (missing(onDependsMetadata)) return '';
    let t = type(onDependsMetadata);
    if (t === 'string') {
      onDependsMetadata = JSON.parse(onDependsMetadata);
    }
    t = type(onDependsMetadata);
    if (t === 'array') {
      onDependsMetadata.forEach(metadata => functionBody = functionBody + '\n' + this.createOnDependsFunctionBody(metadata));
    } else if (t === 'object') {
      if (!onDependsMetadata.isTable) {
        for (let field of onDependsMetadata.fields) {
          let fields = field.split('.');
          if (fields.length === 1) {
            /**监听主表字段**/
            functionBody = functionBody + '\n' + 'field.templateOptions.componentRef.interceptFrom("' + fields[fields.length - 1] + '", "' + onDependsMetadata.method + '");';
          } else if (fields.length > 1) {
            /**监听从表字段**/
            functionBody = functionBody + '\n' + 'field.templateOptions.componentRef.interceptTable("' + fields[fields.length - 2] + '", "' + fields[fields.length - 1] + '", "' + onDependsMetadata.method + '");';
          }
        }
      }
    }
    return functionBody;
  }

  public navigateToForm(item) {
    item.wfFlag = true; // 设置 wfFlag 为true
    const formId = item.formId;
    const url = '/' + formId;
    if (this.rs.exists(url) || this.rs.curUrl === url) {
      this.events.publish(formId, item);
      this.events.publish('drawer'); // 用于处理弹框跳连接弹框关闭
      this.router.navigateByUrl(formId);
    } else {
      this.formData['key'] = item;
      this.events.publish('drawer'); // 用于处理弹框跳连接弹框关闭
      this.router.navigate([formId]);
    }
  }
}
